<template>
    <div class="history">
        <div class="chart" ref="chart">



        </div>


    </div>
</template>
<script>
export default {
    props: {
    checked: {
      type: Boolean,
      default: () => false,
    },
    WarnValue: {
      type: Number,
      default: () => 300,
    },
    tel: {
      type: String,
      default: () => "",
    },
  },
    mounted() {
        this.$ipcRenderer.on_phHistory_reply(
            (phHistory) => {
                this.$nextTick().then((data) => {
                    let Data = phHistory.map((item) => {
                        // console.log(this.transTimestamp(item["time"]));
                        return {
                            ...item,
                            time: this.transTimestamp(item["time"], "-"),
                        };
                    })
                    let list = Data.sort((a,b)=>{
                        //return b.id - a.id
                       return a.id - b.id
                    });
                    console.log("🚀 ~ list ~ list:", list)

                  if(list.length>10){//10条以上数据再处理 resver 会对原数组操作
                    this.processCurrentTenData(JSON.parse(JSON.stringify(Data)).reverse().slice(0, 10))
                  }

                    this.drawChart(list);
                });
            }
        );

    },
    data() {
        return {
            visible: false,
            title: "",
            myChart: null, chartBox:null

        };
    },
    methods: {
        resizeChart(){
  if(this.myChart == null) return;
  this.$nextTick(_ => {
    this.myChart.resize({
          // 根据父容器的大小设置大小
          width: this.$refs.chart.clientWidth,
          height: this.$refs.chart.clientHeight,
        });
  })
},
        processCurrentTenData(list) {
            //PH结果连续10次接收数据波动过大
            let warn = true;
            for (let index = 0; index < list.length - 1; index++) {
                if (list[index].pH_data - list[index + 1].pH_data <= 0.5) {
                    warn = false
                }

            }


            if (
            warn&& 
            this.checked == true &&
            this.tel !== ""
          ) {
            Axios.get(
              `https://fairsense.tzagility.cn:12346/auth/telmsg?tel=${this.tel}&str=您好,PH结果连续10次接收数据波动过大,请维修`
            ).then((data) => {});

            return
          }
        },



        drawChart(Data) {
            let option = {
                xAxis: {
                    //   name: "nm",
                    data: Data.map((item) => item["time"]),
                    maxInterval: 500,
                }, backgroundColor: "#fff",
                tooltip: {
                    trigger: "axis",
                    valueFormatter: (value) => Number(value).toFixed(3),
                    textStyle: {
                        align: "left",
                    },
                },
                legend: {
                    data: ["PH"],
                },
                grid: {
                    left: "6%",
                    right: "3%",
                    top: "8%",
                    bottom: "20%",
                },

                dataZoom: [
                    {
                        type: "slider", //inside平移 缩放
                        // throttle: '50', //设置触发视图刷新的频率。单位为毫秒（ms）。
                        minValueSpan: 6, //用于限制窗口大小的最小值,在类目轴上可以设置为 5 表示 5 个类目
                        start: 0, //数据窗口范围的起始百分比 范围是：0 ~ 100。表示 0% ~ 100%。
                        end: 100, //数据窗口范围的结束百分比。范围是：0 ~ 100。
                        zoomLock: true, //如果设置为 true 则锁定选择区域的大小，也就是说，只能平移，不能缩放。
                        textStyle: { color: "rgba(0,0,0,0)" },
                    },
                ],
                yAxis: {
                    type: "value",
                    //  name:"ppm",
                    axisLabel: {
                        //    formatter: function (value, index) {
                        //     return Number(value);
                        // }
                    }
                },
                series: [
                    {
                        name: "PH",

                        data: Data.map((item, index) => {
                            return {
                                value: Number(item.pH_data),
                                symbol: (Number(item.pH_data) < 1 || Number(item.pH_data) > 5) ? "circle" : "none",
                                symbolSize: 10,
                                itemStyle: {
                                    color: (Number(item.pH_data) < 1 || Number(item.pH_data) > 5) ? "red" : "#00ff00"
                                }
                            }
                        }
                        ),
                        type: "line",
                        smooth: true,
                        markLine: {
                            symbol: ["none", "none"], //去掉箭头
                            itemStyle: {
                                normal: {
                                    //color: "#0"
                                    lineStyle: { type: "dashed", color: "#00ff00", width: 3 },
                                    label: {
                                        show: true,
                                        position: "middle",
                                                  formatter(value) {
                                                    // return `${value.value}`;
                                            return ``;
                                          }
                                    },
                                },
                            },
                            data: [
                                {
                                    name: "警戒值",
                                    yAxis: 5,
                                },
                                {
                                    name: "警戒值",
                                    yAxis: 1,
                                },
                            ],
                        }
                    },
                ],
            };

            if (this.myChart == null) {  
                this.myChart = this.$echarts.init(this.$refs.chart);
                this.myChart.setOption(option);
                let that = this;
                // 当滑动条变化时触发
                this.myChart.on("datazoom", (params) => {
                    this.$emit('stopRefresh');

                });
                return;
            }

            this.myChart.setOption(option, true); //true重绘
            // this.myChart = this.$echarts.init(this.$refs.chart);
            // this.myChart.setOption(option);
            // return;
        },

        transTimestamp(datetime, dateSeprator = "/", timeSeprator = ":") {
            if (datetime) {
                const date = new Date(datetime);
                const year = `${date.getUTCFullYear()}`;
                let month = `${date.getUTCMonth() + 1}`;
                let day = `${date.getUTCDate()}`;
                let hour = `${date.getUTCHours()}`;
                let minute = `${date.getUTCMinutes()}`;
                let second = `${date.getUTCSeconds()}`;
                if (month.length === 1) {
                    month = `0${month}`;
                }
                if (day.length === 1) {
                    day = `0${day}`;
                }
                if (day.length === 1) {
                    day = `0${day}`;
                }
                if (hour.length === 1) {
                    hour = `0${hour}`;
                }
                if (minute.length === 1) {
                    minute = `0${minute}`;
                }
                if (second.length === 1) {
                    second = `0${second}`;
                }
                return `${year}${dateSeprator}${month}${dateSeprator}${day} ${hour}${timeSeprator}${minute}${timeSeprator}${second}`;
            }
        },
    },
};
</script>

<style lang="less" scoped>
.history {
    height: 100%;
    width: 100%;

}

.chart {

    height: 100%;
    width: 100%;
     background-color: #fff;
}
</style>